package com.feiyutech.camera2demo

import android.media.ImageReader
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.util.*
import kotlin.concurrent.thread



/**
 * 描述:
 * 时间: 2018/8/4 23:05
 * 作者: zengfansheng
 */
class JpegReaderListener(private val listener: OnSaveResultListener?) : ImageReader.OnImageAvailableListener {    
    override fun onImageAvailable(reader: ImageReader?) {
        if (reader != null) {
            thread {
                val image = reader.acquireLatestImage()
                try {
                    val buffer = image.planes[0].buffer
                    val bytes = ByteArray(buffer.remaining())
                    buffer.get(bytes)
                    val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "${UUID.randomUUID()}.jpg")
                    val out = FileOutputStream(file)
                    out.write(bytes)
                    out.close()
                    listener?.onSaveResult(file)                    
                } catch (e: Exception) {
                    e.stackTrace                    
                    listener?.onSaveResult(null)
                } finally {
                    image.close()
                }
            }
        }
    }
    
    interface OnSaveResultListener {
        /**
         * 失败时file=null
         */
        fun onSaveResult(file: File?)
    }
}